package bro2Advanced.threads;

public class volatileTest {
    public  int inc = 0;

    public void increase() {
        inc++;
    }

    public static void main(String[] args) {
        final volatileTest test = new volatileTest();
        for (int i = 0; i < 10; i++) {
            new Thread() {
                public void run() {
                    for (int j = 0; j < 1000; j++)
                        test.increase();
                };
            }.start();
        }
        while (Thread.activeCount() > 2){
            Thread.yield();
        }  //保证前面的线程都执行完
        System.out.println("inc output:" + test.inc);
    }

}

/**
 * "双重检查锁定"（double-checked locking）实现的单例模式
 */
class Penguin {
    private static volatile Penguin m_penguin = null;

    private int money = 10_000;

    // 避免通过 new 初始化对象，构造方法应为 public 或 private
    private Penguin(){}

    public void beating() {
        System.out.println("打豆豆" + money);
    }

    public static Penguin getInstance() {
        if(m_penguin == null) {
            synchronized (Penguin.class) {
                if(m_penguin == null) {
                    m_penguin = new Penguin();
                }
            }
        }
        return m_penguin;
    }
}